<template>
    <div class="sale_where">
        <span>盘点单号：</span><el-input class="sale_input" v-model="qty_code"
            style="width: 240px;margin-right: 20px;" />
        <span>盘点类型：</span>
        <el-select v-model="qty_type" placeholder="请选择" class="select-style" style="width: 240px;margin-right: 20px;">
            <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"
                class="option-style" />
        </el-select>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button @click="reset">重置</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }" :span-method="objectSpanMethod">
        <el-table-column prop="qty_code" label="盘点单号" width="160px" fixed="left">
            <template #default="scope">
                <span style="cursor: pointer; color: #409EFF;" @click="GoQtyInfo(scope.row.qty_code)">
                    {{ scope.row.qty_code }}
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="qty_type" label="盘点类型" width="110px">
            <template #default="scope">
                <el-tag>{{ measure_qty_type(scope.row.qty_type) }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column width="180px" prop="warehouse_name" label="仓库名称" />
        <el-table-column width="180px" prop="qty_startdate" label="盘点开始时间" />
        <el-table-column width="180px" prop="qty_end" label="盘点结束时间" />
        <el-table-column width="180px" prop="inventory_numder" label="盘点数量" />
        <el-table-column width="180px" prop="proddti_profit" label="盘盈数量" />
        <el-table-column width="180px" prop="proddti_loss" label="盘亏数量" />
        <el-table-column width="180px" prop="qty_clerk" label="盘点人" />
    </el-table>
    <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script>
import axios from 'axios'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { useWarehouseStore } from '@/storejs/warehouseStore';
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const tableData = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const options = ref([])
        const store = useStore()
        const router = useRouter()
        const qty_type = ref("")
        const qty_code = ref("")

        onMounted(() => {
            getClassify()
            fill()
            count()
        })

        function fill() {
            axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_selectFY", {
                params: {
                    currentPage: currentPage.value,
                    pageSize: pageSize.value,
                    qty_code: qty_code.value,
                    qty_type: qty_type.value,
                    proName: props.detailsData
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                tableData.value = transformQtyData(result.data)
                console.info(result.data.details)
            }).catch((err) => {
                console.info(err)
            });
        }

        // 数据转换方法 - 适配盘点数据结构
        const transformQtyData = (responseData) => {
            const result = []

            responseData.forEach((mainItem) => {
                mainItem.details.forEach((detail, index) => {
                    if (detail.pro_code == props.detailsData) {
                        result.push({
                            qty_end: formatTime(mainItem.qty_end),
                            qty_id: mainItem.qty_id,
                            qty_code: mainItem.qty_code,
                            qty_type: mainItem.qty_type,
                            warehouse_name: mainItem.warehouse_name,
                            qty_clerk: mainItem.qty_clerk,
                            qty_startdate: formatTime(mainItem.qty_startdate),
                            qty_audit_status: mainItem.qty_audit_status,
                            qty_audit_opinion: mainItem.qty_audit_opinion,
                            pro_name: detail.pro_name,
                            pro_code: detail.pro_code,
                            pro_brand: detail.pro_brand,
                            pro_model: detail.pro_model,
                            unit: detail.unitmeas_id,
                            inventory_numder: detail.inventory_numder,
                            proddti_loss: detail.proddti_loss,
                            proddti_profit: detail.proddti_profit,
                        })
                    }

                })
            })

            return result
        }

        function count() {
            axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_selectCount", {
                params: {
                    qty_code: qty_code.value,
                    qty_type: qty_type.value,
                    proName: props.detailsData
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            fill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            fill();
        }

        // 获取下拉选项数据 - 盘点类型
        function getClassify() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "inv_qty"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                options.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        // 盘点类型字典转换
        function measure_qty_type(row) {
            if (!row) return "无";
            const type = options.value.find((item) => item.dict_value == row);
            return type ? type.dict_label : "无";
        }

        function formatTime(time) {
            return time?.replace('T', ' ') || ''; // 安全处理空值
        }

        function query() {
            fill()
            count()
        }

        function reset() {
            qty_code.value = ""
            qty_type.value = ""
            query()
        }

        function formatTime(time) {
            return time?.replace('T', ' ') || ''; // 安全处理空值
        }

        function GoQtyInfo(qty_code) {
            const warehouseStore = useWarehouseStore();
            warehouseStore.qty_code = qty_code;
            router.push('/main/Inv/InvQtyDetails');
        }

        return {
            tableData, currentPage, pageSize, pageCount, handleCurrentChange, handleSizeChange, query, reset, measure_qty_type,
            measure_qty_type, options, GoQtyInfo, qty_code, qty_type,
        }
    }
}
</script>

<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}

.sale_where {
    margin: 15px 0px;
    text-align: center;
    float: left;
}
</style>